<script>
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import request from '@/utils/request.js'
import { ElMessageBox } from 'element-plus'

export default {
  name: 'NovelDetail',
  setup() {
    const route = useRoute()
    const novelId = route.params.id
    const novel = ref({})
    const comments = ref([])
    const textarea = ref('')
    const rating = ref(0)
    const userId = ref(1)
    const input = ref('')

    const getNovelDetail = async () => {
      try {
        const response = await request.get(`/novel/${novelId}`)
        if (response.code === 1) {
          novel.value = response.data
        } else {
          console.error(response.msg || '获取小说详情失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const getComments = async () => {
      try {
        const response = await request.get(`/comment/page?novelId=${novelId}`)
        if (response.code === 1) {
          comments.value = response.data.list
        } else {
          console.error(response.msg || '获取评论失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const addComment = async () => {
      try {
        const response = await request.post('/comment/add', {
          novelId: novelId,
          userId: userId.value,
          content: textarea.value,
          rating: rating.value
        })
        if (response.code === 1) {
          console.log('评论成功')
          // 清空输入框
          textarea.value = ''
          rating.value = 0
          // 刷新评论列表
          getComments()
        } else {
          console.error(response.msg || '评论失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const reportComment = (commentId) => {
      ElMessageBox.prompt('请输入举报理由', '举报评论', {
        confirmButtonText: '提交',
        cancelButtonText: '取消',
        inputPlaceholder: '请在此输入举报理由',
        inputValidator: (value) => value.length > 0 && value.length <= 100,
        inputErrorMessage: '举报理由不能为空且不超过100字',
      }).then(({ value }) => {
        reportCommentToServer(commentId, value)
      }).catch(() => {
        console.log('取消举报')
      })
    }

    const reportCommentToServer = async (commentId, reason) => {
      try {
        const response = await request.post('/report/add', {
          commentId: commentId,
          reason: reason
        })
        if (response.code === 1) {
          console.log('举报成功')
        } else {
          console.error(response.msg || '举报失败')
        }
      } catch (error) {
        console.error('服务异常')
      }
    }

    const formatTime = (time) => {
      return time.replace('T', ' ')
    }

    onMounted(() => {
      getNovelDetail()
      getComments()
    })

    return {
      novel,
      comments,
      textarea,
      rating,
      userId,
      addComment,
      reportComment,
      formatTime
    }
  }
}
</script>

<template>
  <div class="novel-detail-container">
    <div class="novel-info">
      <div class="left">
        <h1>{{ novel.title }}</h1>
        <p><strong>作者：</strong>{{ novel.authorName }}</p>
        <img :src="novel.avatar" alt="封面" style="width: 200px; height: auto;">
      </div>
      <div class="right">
        <br><br><br>
        <p><strong>类别：</strong>{{ novel.category }}</p>
        <p><strong>发布日期：</strong>{{ novel.publishTime }}</p>
        <p><strong>评分：</strong>{{ novel.rating }}</p>
        <p><strong>描述：</strong>{{ novel.description }}</p>
      </div>
    </div>

    <h2>发表评论</h2>
    <div class="rate-block">
      <span class="demonstration">评分</span>
      <el-rate v-model="rating" />
      <p class="rate-description">请为这部小说打分</p>
    </div>
    <el-input
      v-model="textarea"
      maxlength="200"
      style="width: 100%"
      placeholder="请输入评论内容"
      show-word-limit
      type="textarea"
    />
    <el-button type="primary" @click="addComment">发送评论</el-button>

    <h2>评论</h2>
    <el-scrollbar height="400px">
      <div v-for="comment in comments" :key="comment.id" class="scrollbar-demo-item">
        <div class="comment-header">
          <span class="username">{{ comment.userName }}</span>
          <div class="rating-time">
            <el-rate v-model="comment.rating" disabled />
            <span class="create-time">{{ formatTime(comment.createTime) }}</span>
          </div>
        </div>
        <p class="comment-content">{{ comment.content }}</p>
        <div class="comment-footer">
          <el-button type="text" @click="reportComment(comment.id)">举报</el-button>
        </div>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped>
.novel-detail-container {
  padding: 20px;
}

.novel-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.left {
  flex: 1;
  margin-right: 20px;
}

.right {
  flex: 1;
}

.scrollbar-demo-item {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  justify-content: space-between;
  margin: 10px 0;
  padding: 10px;
  border-radius: 4px;
  background: var(--el-color-primary-light-9);
  color: var(--el-color-primary);
  position: relative;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  width: 100%;
}

.username {
  font-weight: bold;
}

.rating-time {
  display: flex;
  align-items: center;
}

.create-time {
  margin-left: 10px;
  color: var(--el-text-color-secondary);
  font-size: 12px;
}

.comment-content {
  margin-top: 10px;
}

.comment-footer {
  display: flex;
  justify-content: flex-end;
  width: 100%;
  margin-top: 10px;
}

.rate-block {
  margin: 20px 0;
}

.demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 10px;
}

.rate-description {
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-top: 5px;
}

</style>